package gold.digger;

import gold.utils.InputUtil;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC135 {
    public long startExecuteTime = System.currentTimeMillis();

    /*
     * @param 此题目参考了别人代码
     * 这是因为问题情况较为复杂
     * 未来需要再次复习此道题目
     * @return:
     */

    public class Solution {
        public int count(int n) {
            return (n * (n + 1)) / 2;
        }

        public int candy(int[] ratings) {
            if (ratings.length <= 1) {
                return ratings.length;
            }
            int candies = 0;
            int up = 0;
            int down = 0;
            int old_slope = 0;
            for (int i = 1; i < ratings.length; i++) {
                int new_slope = (ratings[i] > ratings[i - 1]) ? 1 : (ratings[i] < ratings[i - 1] ? -1 : 0);
                if ((old_slope > 0 && new_slope == 0) || (old_slope < 0 && new_slope >= 0)) {
                    candies += count(up) + count(down) + Math.max(up, down);
                    up = 0;
                    down = 0;
                }
                if (new_slope > 0)
                    up++;
                if (new_slope < 0)
                    down++;
                if (new_slope == 0)
                    candies++;

                old_slope = new_slope;
            }
            candies += count(up) + count(down) + Math.max(up, down) + 1;
            return candies;
        }
    }


    class Solution_Fail {
        public int candy(int[] ratings) {
            if (ratings.length <= 1) return ratings.length;

            int count = ratings.length;
            int base = 1;
            for (int i = 1; i < ratings.length - 1; i++) {
                if (ratings[i] > ratings[i - 1] || ratings[i] > ratings[i + 1]) count += base++;
                else base = 1;
            }

            if (ratings.length >= 2 && ratings[0] > ratings[1]) ++count;
            if (ratings.length >= 3 && ratings[ratings.length - 1] > ratings[ratings.length - 2]) ++count;

            return count;
        }
    }


    public void run() {
        Solution solution = new Solution();
        int[] arr = InputUtil.toIntegerArray("[29,51,87,87,72,12]");
        System.out.println(solution.candy(arr));
    }

    public static void main(String[] args) throws Exception {
        LC135 an = new LC135();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
